<?php

namespace App\Admin\Controllers;

use App\Admin\Extensions\ExcelExpoter;
use App\Models\Order;
use App\Models\User;
use App\Models\UserAdmin;
use Illuminate\Support\Facades\Hash;
use Encore\Admin\Form;
use Encore\Admin\Grid;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Layout\Content;
use App\Http\Controllers\Controller;
use Encore\Admin\Controllers\ModelForm;
use Illuminate\Support\Facades\Redis;
use Illuminate\Support\Facades\DB;

class UserController extends Controller
{
    use ModelForm;

    /**
     * Index interface.
     *
     * @return Content
     */
    public function index()
    {
        return Admin::content(function (Content $content) {

            $content->header('用户管理');
            $content->description('');

            $content->body($this->grid());
        });
    }

    // demo 统计数据
    public function analysis(){
        return Admin::content(function (Content $content) {

            $content->header('用户分析');
            $content->description('具体信息如下');
            $content->body(view('admin.user.analysis'));
        });
    }
    public function checkfinance(){
        return Admin::content(function (Content $content) {

            $content->header('资金检查');
            $content->description('');
            $content->breadcrumb(
                ['text' => '资金检查', 'url' => '/users/checkfinance'],
                ['text' => '']
            );
            $content->body($this->gridFinance());
        });
    }
    protected function gridFinance()
    {
        return Admin::grid(User::class, function (Grid $grid) {
            $grid->filter(function($filter){
                // 去掉默认的id过滤器
                $filter->disableIdFilter();
                $filter->like('name', '用户名称');
            });
            $grid->model()->orderBy('id', 'desc');
            $grid->id('ID')->sortable();
            $grid->column('name','用户名称');
            $grid->column('money','资金');
            $grid->column('point','积分');
            $grid->column('created_at', '创建时间');
            $grid->disableCreateButton();
            $grid->actions(function ($actions) {
                $actions->disableDelete();
                $actions->disableEdit();
                $user_id = $actions->getKey();
                $actions->append('<a href="/admin/cash/someone?user_id='.$user_id.'"><i class="fa fa-eye">查看提现记录</i></a>');
                $actions->append('&nbsp;&nbsp;<a href="/admin/users/cash?user_id='.$user_id.'"><i class="fa fa-eye">资金增减</i></a>');
            });
        });
    }
    public function edit($id)
    {
        return Admin::content(function (Content $content) use ($id) {

            $content->header('编辑用户');
            $content->description('');

            $content->body($this->form()->edit($id));
        });
    }
    /**
     * Make a form builder.
     *
     * @return Form
     */
    protected function form()
    {
        return Admin::form(UserAdmin::class, function (Form $form) {

            $form->saving(function (Form $form) {
                if(!request()->route()->parameters()) {
                    $user = User::where('mobile', $form->mobile)->first();
                    if ($user) {
                        echo "<script> alert('该用户已存在！');history.back(); </script>";
                        die;
                    }
                }

                //资金增减
                if ($form->add_money) {
                    $add_money = $form->add_money;
                    $add_money = ltrim($add_money, "-");
                    $money = User::where('id',request()->route()->parameters())->first()->money;
                    if($add_money>$money && $form->type==0){
                        echo "<script> alert('支出金额高于余额！');history.back(); </script>";
                        die;
                    }
                    if($form->type==0){
                        $change_money = $money - $add_money;
                    }else{
                        $change_money = $money + $add_money;
                    }
                    if(!$form->sign){
                        $sign = '后台'.Admin::user()->username.'操作';
                    }else{
                        $sign = '后台'.Admin::user()->username.'操作：'.$form->sign;
                    }
                    // DB::beginTransaction();
                    //  try{
                    $data1 = DB::table('users')
                        ->where('id',request()->route()->parameters()['user'])
                        ->update(['money'=>$change_money]);

                    $data2 = DB::table('wallet_logs')->insert([
                        'serial_number' => Admin::user()->username,
                        'user_id' => request()->route()->parameters()['user'],
                        'type' => $form->type,
                        'work_capital' => $form->add_money,
                        'now_money' => $change_money,
                        'sign' => $sign,
                        'note' => '资金增减',
                        'trace_way' => 0,
                        'created_at' => date("Y-m-d H:i:s"),
                        'updated_at' => date("Y-m-d H:i:s")
                    ]);
                    if($data1 && $data2){
                        DB::commit();
                        echo "<script> alert('保存成功！');history.go(-2); </script>";
                        die;
                    }
                    //  }catch (\Exception $e){
                    /*DB::rollBack();
                    echo $e->getMessage();
                    echo $e->getCode();*/
                    //    }
                }

            });
            $form->saved(function (Form $form) {
                if($form->password){
                    $password = Hash::make($form->password);
                    User::where('mobile',$form->mobile)->update(['password'=>$password]);
                }
                if($form->payword){
                    $payword = Hash::make($form->payword);
                    User::where('mobile',$form->mobile)->update(['payword'=>$payword]);
                }
                if($form->money==null){
                    User::where('mobile',$form->mobile)->update(['money'=>0]);
                }
                if($form->point==null){
                    User::where('mobile',$form->mobile)->update(['point'=>0]);
                }
            });
            $form->display('id', 'ID');
            $form->text('pid', '推荐人id');
            $form->text('mobile', '账号')->rules('required');
            $form->text('name', '昵称')->rules('required');
            if(count(request()->route()->parameters())==0) {
                $form->text('password', '登录密码');
                $form->text('payword', '支付密码');
            }else{
                $form->password('password', '登录密码');
                $form->password('payword', '支付密码');
            }
            $data = User::all();
            $res = array();
            foreach ($data as $key => $value) {
                $res[$value['id']] = $value['mobile'];
            }
            $form->text('money', '用户金额');
            $form->text('point', '用户积分');
            $form->radio('sex', '性别')->options(['0' => '男', '1'=> '女'])->default('0');
            $form->radio('role', '角色')->options(['0' => '个人用户', '1'=> '企业或商家', '2'=>'合伙人'])->default('0');
            //$form->image('avatar', '头像');
            $form->text('userinfosys.id_card', '身份证');
            $form->text('userinfosys.real_name', '真实姓名');
            $form->text('userinfosys.email', '联系邮箱');
            $form->hasMany("cashconfig", "添加银行卡",function ($form) {
                $form->select('account_type', '提现类型')->options([0 => '银行卡', 1 => '支付宝', 2 => '微信']);
                $form->text('bank', '银行');
                $form->text('account_number', '卡号');
                $form->text('account_user', '所有人');
            });
        });
    }

    protected function editform()
    {
        return Admin::form(User::class, function (Form $form) {

            $form->display('id', 'ID');
            $form->text('mobile', '账号')->rules('required');
            $form->text('name', '昵称');
            /*$form->password('password', '登录密码');
            $form->password('payword', '支付密码');*/
            $form->radio('sex', '性别')->options(['0' => '男', '1'=> '女'])->default('0');
            $form->radio('role', '角色')->options(['0' => '个人用户', '1'=> '企业或商家', '2'=>'合伙人'])->default('0');
            //$form->image('avatar', '头像');
            $form->text('money', '用户金额');
            $form->text('userInfoSys.id_card', '身份证');
            $form->text('userInfoSys.real_name', '真实姓名');
            $form->text('userInfoSys.email', '联系邮箱');
        });
    }


    /**
     * Make a grid builder.
     *
     * @return Grid
     */
    protected function grid()
    {
        return Admin::grid(User::class, function (Grid $grid) {
            $excel = new ExcelExpoter();
            $excel->setAttr(
                ['id', '角色（0个人1商家2合伙人）','账号','昵称','用户金额','用户积分','真实姓名','身份证','创建时间'],
                ['id', 'role','mobile','name','money','point','userinfosys.real_name','userinfosys.id_card','created_at'],'用户资料'
            );
            $grid->exporter($excel);
            $grid->filter(function($filter){
                // 去掉默认的id过滤器
                $filter->disableIdFilter();
                $filter->like('mobile', '账号');
                $filter->like('name', '昵称');
                $filter->like('userInfoSys.real_name', '真实姓名');
            });
            $grid->column('id', '用户id');
            $grid->column('role','角色')->display(function ($role){
                if ($role == '0'){
                    return "<span class='badge bg-teal-gradient'>个人</span>";
                }elseif ($role == '1'){
                    return "<span class='badge bg-yellow-gradient'>商家</span>";
                }else if ($role == '2'){
                    return "<span class='badge bg-black-gradient'>合伙人</span>";
                }else{
                    return "<span class='badge bg-blue-gradient'>无效角色</span>";
                }
            });

            $grid->column('mobile', '账号');
            $grid->column('name', '昵称');
            $grid->column('money', '用户金额');
            $grid->column('point', '用户积分');
            $grid->column('userInfoSys.real_name','真实姓名')->display(function ($name){
                return isset($name) ? $name:'无';
            });
            $grid->column('userInfoSys.id_card','身份证')->display(function ($card){
                return isset($card) ? $card:'无';
            });
            $grid->column('created_at', '创建时间');
            $grid->actions(function ($actions) {
                $user_id = $actions->getKey();
                $actions->prepend('<a href="/admin/orders/user?user_id='.$user_id.'"><i class="fa fa-eye">查看订单</i></a>');
                $actions->prepend('<a href="/admin/shops/create?user_id='.$user_id.'"><i class="fa fa-eye">创建商铺</i></a>');
                $actions->prepend('&nbsp;&nbsp;<a href="/admin/users/cash?user_id='.$user_id.'"><i class="fa fa-eye">资金增减</i></a>');
            });
//            $grid->paginate(2);
        });
    }
    public function editFinance()
    {
        dd('hello');
    }
    public function editFinancePage()
    {
        return Admin::content(function (Content $content) {

            $content->header('资金增减');
            $content->description('');
            $content->breadcrumb(
                ['text' => '资金检查', 'url' => '/users/checkfinance'],
                ['text' => '']
            );
            $content->body($this->editfinanceform()->edit(\request('user_id')));
        });
    }

    protected function editfinanceform()
    {
        return Admin::form(User::class, function (Form $form) {

            $form->setAction('/admin/users/'.request('user_id'));
//            $form->setAction('/admin/users/editfinance');
            //$form->display('id', 'ID');
            $form->display('name', '用户名');
            $form->display('money', '余额');
            $form->radio('type','类型')->options(['0' => '支出', '1'=> '收入']);
            $form->currency('add_money', '增减金额')->symbol('￥')->rules('required|in');
            $form->textarea('sign', '备注')->rows('3');
//            $form->text('updated_at', '更新时间');
        });
    }
    /**
     * Create interface.
     *
     * @return Content
     */
    public function create()
    {
        return Admin::content(function (Content $content) {

            $content->header('创建用户');
            $content->description('详细信息');

            $content->body($this->form());
        });
    }

    public function lyj()
    {
        return '你好';
    }


}
